import Tkinter as gui
import Pmw

root = None

class _Label(object):
   def __init__(self, parent, text):
      self.parent = parent
      self.var = gui.StringVar()
      self.var.set(text)
      self.widget = gui.Label(parent.view.widget, textvariable=self.var)
   def set(self, value):
      self.var.set(value)

class _Button(object):
   def __init__(self, parent, text):
      self.parent = parent
      self.var = gui.StringVar()
      self.var.set(text)
      self.widget = gui.Button(parent.view.widget, textvariable=self.var, command=self.command)
   def command(self):
      self.parent.value = self.var.get()
   def set(self, value):
      self.var.set(value)

class _Check(object):
   def __init__(self, parent, text):
      self.parent = parent
      self.var = gui.StringVar()
      self.var.set(0)
      self.widget = gui.Checkbutton(parent.view.widget, text=text, variable=self.var)
   def get(self):
      return self.var.get() == '1'
      
class _Entry(object):
   def __init__(self, parent):
      self.parent = parent
      self.var = gui.StringVar()
      self.widget = gui.Entry(parent.view.widget, textvariable=self.var)
      self.widget.bind('<Return>', self._command)
   def _command(self, event):
      self.parent.value = self.var.get()
   def set(self, v):
      self.var.set(v)
   def get(self):
      return self.var.get()
      
class _List(object):
   def __init__(self, parent):
      self.parent = parent
      self.widget = Pmw.ScrolledListBox(parent.view.widget,selectioncommand=self._command)
   def _command(self):
      self.parent.value = self.widget.getvalue()[0]
   def set(self, arg):
      self.widget.setlist(arg)
   def get(self):
      return self.widget.getvalue()
      
def gridded(widget):
   parent = widget.parent
   widget.widget.grid (row=parent.r, column=parent.c, rowspan=parent.rows, columnspan=parent.cols)
   return widget

def Button(parent, text):
   return gridded ( _Button(parent, text))

def Check(parent, text):
   return gridded( _Check(parent, text) )

def Entry(parent):
   return gridded( _Entry(parent) )
   
def Label(parent, text):
   return gridded( _Label(parent, text) )

def List(parent):
   return gridded( _List(parent) )

def start():
   assert root
   root.mainloop()

def quit():
   assert root
   root.quit()
   
def View(parent):
   global root
   if root is None:
      root = gui.Tk()
      return root
   else:
      return gui.Toplevel()
   
